package batch.import_user;

import java.sql.*;
import java.io.*;
import java.net.URLEncoder;
import java.net.URL;
import java.net.HttpURLConnection;

import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.dbutils.*;
import org.apache.log4j.*;

import batch.common.secui.*;
import batch.common.db.ConnectionManager;
import batch.common.util.*;

public class importDataForGbrwhPostnAd
{
    private final String TRPLKEY     = "QWERTYUIOP!@#$%^&*()aaaa";

    private final String TABLE_NAME  = "G_GBR_IMPORT_TEMP_2";
    private final String HP_BRAND_YM = "Y";
    private final String MEMBERGBN   = "10507101";  //10507101 - My Offer

    private final String LANGUAGE    = "ENG";
    private final String COUNTRY     = "0102064";
    private final String REG_COUNTRY = "0102064";
    private final String NEWS_LETTER = "Y";
    private final String RESERVED3   = "N";
    private final String HP_BRAND    = "0103001";

    public static void main(String[] args)
    {
        Logger.getLogger("import_user.importDataForGbrwhPostnAd").info("( * ) Start.");

        importDataForGbrwhPostnAd obj = new importDataForGbrwhPostnAd();
        obj.init();

        Logger.getLogger("import_user.importDataForGbrwhPostnAd").info("( * ) End.");
    }

    public void init() {
        StringBuffer sQuery = new StringBuffer()
                             .append("SELECT SEQ                                  \n")
                             .append("     , USERID                               \n")
                             .append("     , PASSWD                               \n")
                             .append("     , FNAME                                \n")
                             .append("     , LNAME                                \n")
                             .append("     , NVL(GENDER, 'M')                     \n")
                             .append("     , EMAIL                                \n")
                             .append("     , BIRTHDAY                             \n")
                             .append("     , ADDRESS                              \n")
                             .append("     , POSTCODE                             \n")
                             .append("     , HP_BRAND                             \n")
                             .append("  FROM " + TABLE_NAME + "                   \n")

                             //.append(" WHERE USERID IS NOT NULL                   \n")
                             //.append("   AND PASSWD IS NOT NULL                   \n")
                             //.append("   AND FNAME IS NOT NULL                    \n")
                             //.append("   AND LNAME IS NOT NULL                    \n")
                             //.append("   AND BIRTHDAY IS NOT NULL                 \n")
                             //.append("   AND GUBN IS NULL                         \n");

                             .append(" WHERE GUBN IN ('7', '97 id', '97 passwd') \n");

                             //.append(" WHERE GUBN = '99'                          \n");

        StringBuffer sbParameters = new StringBuffer();
        String currentServer = (Conf.getConf("server").indexOf("www") >= 0) ? "www" : "dev";

        Connection conn   = null;
        Statement  stmt   = null;
        ResultSet  rs     = null;

        String seq          = "";
        String id           = "";
        String id_real      = "";
        String password     = "";
        String firstname    = "";
        String lastname     = "";
        String birthday     = "";
        String email        = "";
        String hp_model     = "";
        String hp_imei      = "";
        String hp_sn        = "";
        String hp_num       = "";
        String countrycode  = "";
        String hp_provider  = "";
        String hp_buy_ym    = "";
        String gender       = "";
        String recommend_id = "";
        String address      = "";
        String postcode     = "";
        String sHpBrand     = "";

        String strLine      = "";
        String strResult    = "";
        int    i            = 0;

        BufferedReader in = null;
        PrintWriter pwServelt = null;

        try{
            TripleDES tplDES = new TripleDES(TRPLKEY);

            conn = ConnectionManager.getConnection();
            conn.setAutoCommit(true);
            stmt= conn.createStatement();
            rs = stmt.executeQuery(sQuery.toString());

            QueryRunner qRunner = new QueryRunner();

            URL urlOpen = new URL("http://" + currentServer + ".samsungmobile.com/integration/user_profile/register_user");

            while (rs.next()) {
                i++;

                strResult = "";
                seq       = ObjectUtils.toString(rs.getObject(1));
                id_real   = ObjectUtils.toString(rs.getObject(2));
                id        = tplDES.encrypt(id_real);
                password  = tplDES.encrypt(ObjectUtils.toString(rs.getString(3)));
                firstname = new String(ObjectUtils.toString(rs.getObject(4)).getBytes("UTF-8"), "ISO-8859-1");
                lastname  = new String(ObjectUtils.toString(rs.getObject(5)).getBytes("UTF-8"), "ISO-8859-1");
                birthday  = ObjectUtils.toString(rs.getObject(8));
                email     = tplDES.encrypt(ObjectUtils.toString(rs.getObject(7)));
                gender    = ObjectUtils.toString(rs.getObject(6));
                address   = new String(ObjectUtils.toString(rs.getObject(9)).getBytes("UTF-8"), "ISO-8859-1");
                postcode  = new String(ObjectUtils.toString(rs.getObject(10)).getBytes("UTF-8"), "ISO-8859-1");
                sHpBrand  = ObjectUtils.toString(rs.getObject(11));

                HttpURLConnection httpUrlConn = (HttpURLConnection)urlOpen.openConnection();
                httpUrlConn.setRequestMethod("POST");
                httpUrlConn.setDoOutput(true);
                pwServelt = new PrintWriter(httpUrlConn.getOutputStream());

                //encode the message
                sbParameters.setLength(0);
                sbParameters.append("id="          ).append(URLEncoder.encode(id           , "ISO-8859-1"))
                            .append("&passwd="     ).append(URLEncoder.encode(password     , "ISO-8859-1"))
                            .append("&fname="      ).append(URLEncoder.encode(firstname    , "ISO-8859-1"))
                            .append("&lname="      ).append(URLEncoder.encode(lastname     , "ISO-8859-1"))
                            .append("&birthday="   ).append(URLEncoder.encode(birthday     , "ISO-8859-1"))
                            .append("&country="    ).append(URLEncoder.encode(COUNTRY      , "ISO-8859-1"))
                            .append("&email="      ).append(URLEncoder.encode(email        , "ISO-8859-1"))
                            .append("&reg_country=").append(URLEncoder.encode(REG_COUNTRY  , "ISO-8859-1"))
                            .append("&news_letter=").append(URLEncoder.encode(NEWS_LETTER  , "ISO-8859-1"))
                            .append("&reserved3="  ).append(URLEncoder.encode(RESERVED3    , "ISO-8859-1"))
                            .append("&hp_model="   ).append(URLEncoder.encode(hp_model     , "ISO-8859-1"))
                            .append("&hp_brand="   ).append(URLEncoder.encode(HP_BRAND     , "ISO-8859-1"))
                            .append("&hp_imei="    ).append(URLEncoder.encode(hp_imei      , "ISO-8859-1"))
                            .append("&hp_num="     ).append(URLEncoder.encode(hp_num       , "ISO-8859-1"))
                            .append("&hp_provider=").append(URLEncoder.encode(hp_provider  , "ISO-8859-1"))
                            .append("&hp_buy_ymd=" ).append(URLEncoder.encode(hp_buy_ym    , "ISO-8859-1"))
                            .append("&hp_sn="      ).append(URLEncoder.encode(hp_sn        , "ISO-8859-1"))
                            .append("&membergbn="  ).append(URLEncoder.encode(MEMBERGBN    , "ISO-8859-1"))
                            .append("&gender="     ).append(URLEncoder.encode(gender       , "ISO-8859-1"))
                            .append("&recommend="  ).append(URLEncoder.encode(recommend_id , "ISO-8859-1"))
                            .append("&countrycode=").append(URLEncoder.encode(countrycode  , "ISO-8859-1"))
                            .append("&language="   ).append(URLEncoder.encode(LANGUAGE     , "ISO-8859-1"))
                            .append("&address="    ).append(URLEncoder.encode(address      , "ISO-8859-1"))
                            .append("&postcode="   ).append(URLEncoder.encode(postcode     , "ISO-8859-1"));

                pwServelt.print(sbParameters);

                if(pwServelt != null) try { pwServelt.close(); } catch(Exception se) {}

                in = new BufferedReader(new InputStreamReader(httpUrlConn.getInputStream()));

                while ((strLine = in.readLine()) != null) {
                    strResult = strLine.trim();
                }

                if(in != null) try { in.close(); } catch(Exception se) {}

                sQuery.setLength(0);
                sQuery.append("UPDATE " + TABLE_NAME + "         \n")
                      .append("   SET GUBN = '" + strResult + "' \n")
                      .append(" WHERE SEQ = '" + seq + "'        \n");

                qRunner.update(conn, sQuery.toString());

                if(HP_BRAND_YM.equals("Y") && strResult.equals("0")){
                    sQuery.setLength(0);
                    sQuery.append("INSERT INTO G_GBR_IMPORT_HP_BRAND( USER_NO                         \n")
                          .append("                                 , HP_BRAND)                       \n")
                          .append("                           VALUES( (SELECT USER_NO                 \n")
                          .append("                                      FROM G_MB_MEMBER             \n")
                          .append("                                     WHERE ID = '" + id_real + "') \n")
                          .append("                                 , '" + sHpBrand + "')             \n");

                    qRunner.update(conn, sQuery.toString());
                }

                if( (i%500) == 0){
                    Logger.getLogger("import_user.importDataForGbrwhPostnAd").info("we are here == " + i);
                }

            }
        }
        catch(Exception ex){
            ex.printStackTrace();
            Logger.getLogger("import_user.importDataForGbrwhPostnAd").info(ex.toString());
        }
        finally{
            if(pwServelt != null) try { pwServelt.close(); } catch(Exception se) {}
            if(in        != null) try { in.close();        } catch(Exception se) {}
            if(rs        != null) try { rs.close();        } catch(Exception se) {}
            if(stmt      != null) try { stmt.close();      } catch(Exception se) {}
            if(conn      != null) try { conn.close();      } catch(Exception se) {}
        }
    }
}
